package com.zhi.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import com.zhi.config.Constant;
import com.zhi.entity.*;
import com.zhi.service.*;
import com.zhi.util.MD5Util;
import com.zhi.util.UpdateObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zhi.util.PageUtil;
import com.zhi.util.R;

@Controller
public class UserController {

    Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	UserService userService;
	
	@Autowired
	DictionaryService dictionaryService;

	@Autowired
	StudentService studentService;

	@Autowired
	TeacherService teacherService;

	@Autowired
	FacultyService facultyService;

	@Autowired
	GradeService gradeService;

	@Autowired
	GradeTeacherService gradeTeacherService;


    @RequestMapping("/toUser")
    public String toUser(Model model,PageUtil pageUtil) {
    	
    	//1、初始化分页工具
    	pageUtil = PageUtil.init(pageUtil);
    	Pageable pageable = PageRequest.of(pageUtil.getPageIndex()-1, pageUtil.getSize());
    	
    	//2、查询分页数据
    	Page<User> pageList=userService.getEntityListWithCodeName(pageable);
    	List<User> users = pageList.getContent();
        
        //3、设置总页数
    	pageUtil.setTotalPages(pageList.getTotalPages());
    	
    	//4、返回前台数据
    	model.addAttribute("pageUtil", pageUtil);
        model.addAttribute("users", users);
        return "user/list";
    }

    @RequestMapping("/user/toAdd")
    public String toAdd(Model model) {
    	List<Dictionary> dicts = dictionaryService.getDictsByCodeType("userType");
    	model.addAttribute("dicts", dicts);
        return "user/add";
    }

    @RequestMapping("/user/add")
    @ResponseBody
    public R add(User user) {
        user.setUserState(Constant.EFFECTIVE_YES);//设置了字段默认1-生效，但是报错，有空子再找原因
        user.setPassword(MD5Util.md5Encryption(user.getPassword()));//密码MD5加密)
        userService.save(user);
        return R.ok();
    }

    @RequestMapping("/user/toEdit")
    public String toEdit(Model model,Integer id) {
    	List<Dictionary> dicts = dictionaryService.getDictsByCodeType("userType");
        List<Dictionary> userStateDicts = dictionaryService.getDictsByCodeType("userState");
        User user=userService.getOne(id);
        model.addAttribute("dicts", dicts);
        model.addAttribute("userStateDicts", userStateDicts);
        model.addAttribute("user", user);
        return "user/edit";
    }

    @RequestMapping("/user/edit")
    public String update(User user) {
        User sourceUser = userService.getOne(user.getId());
        //此处查数据库中user数据，并将页面要修改的复制到数据库中的数据，不包含密码
        UpdateObjectUtil.copyNullProperties(user,sourceUser);

        userService.edit(sourceUser);
        return "redirect:/toUser";
    }

    @RequestMapping("/user/delete")
    public String delete(Integer id) {
        userService.delete(id);
        return "redirect:/toUser";
    }

    /**
     * 重置密码
     * @param id
     * @return
     */
    @RequestMapping("/user/resetPassword")
    public String resetPassword(Integer id) {

        //判断用户类型，学生教师密码重置其证件号后6位，管理员密码同用户名
        User user = userService.getOne(id);
        String userType = user.getUserType();
        String clearPassword = "";

        if(Constant.USER_TYPE_STUDENT.equals(userType)){
            //获得学生证件号，截取后6位作为初始密码
            String studentId = user.getUsername();
            Student student = studentService.getOne(studentId);
            String idCardNo = student.getIdCardNo();
            clearPassword = idCardNo.substring(idCardNo.length()-6);//密码明文
        }else if(Constant.USER_TYPE_TEACHER.equals(userType)){
            //获得教师证件号，截取后6位作为初始密码
            String teacherId = user.getUsername();
            Teacher teacher = teacherService.getOne(teacherId);
            String idCardNo = teacher.getIdCardNo();
            clearPassword = idCardNo.substring(idCardNo.length()-6);//密码明文
        } else if(Constant.USER_TYPE_ADMIN.equals(userType)){
            clearPassword = user.getUsername();//密码明文
        }

        user.setPassword(MD5Util.md5Encryption(clearPassword));

        userService.edit(user);

        return "redirect:/toUser";
    }

    
    @RequestMapping("/user/toPersonal")
    public String toPersonal(Model model,HttpSession session) {
    	User sessionUser = (User) session.getAttribute("sessionUser");
    	User user =new User();
    	user.setId(sessionUser.getId());
    	user = userService.findAll(user).get(0);
    	model.addAttribute("user", user);
        return "user/personal";
    }

    /**
     * 个人中心更新密码
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping("/user/editPassword")
    public R editPassword(User user) {

        //保险起见，此处只根据用户id更新密码，username，userType，effective操作
        //1、根据用户id查询数据库中的user对象
//        User sourceUser = userService.getOne(user.getId());
//
//        //2、准备要更新的数据
//        User updateUser = new User(user.getId(),null,user.getPassword(),null,null);
//
//        //3、交换主备更新入库的数据
//        UpdateObjectUtil.copyNullProperties(updateUser,sourceUser);
//
//        //4、密码MD5加密
//        sourceUser.setPassword(MD5Util.md5Encryption(sourceUser.getPassword()));//密码MD5加密)
//
//        //5、更新
//        userService.edit(sourceUser);

        return R.ok();
    }
    
    @ResponseBody
    @RequestMapping("/user/checkUsername")
    public R checkUsername(String username) {
    	User user = new User();
    	user.setUsername(username);
    	Integer num = userService.count(user);
    	if(num > 0) {
    		return R.error("用户名[" + username + "]已存在");
    	}else {
    		return R.ok();
    	}
    }

    /**
     * 个人中心
     * @param model
     * @param httpSession
     * @return
     */
    @RequestMapping("/toPersonalInformation")
    public String toPersonalInformation(Model model,HttpSession httpSession){

        //跳转页面
        String returnPage = "personalStudent";
        User sessionUser = (User)httpSession.getAttribute("sessionUser");
        //要展示的数据
//        //公共
//        String userId = "";//工号
        String username = "";//姓名
//        String userTypeName = "";//用户类型
//        String idCardNo = "";//证件号
//        String email = "";//邮箱

//        //学生特有
//        String facultyName = "";//学院
//        String gradeName = "";//班级
//        String instructor = "";//指导员
//        List<Teacher> teachers = new ArrayList<>();//所有任课教师
//
//        //教师特有
//        String className = "";//所教课程
//        List<Grade> instructorGrades = new ArrayList<>();//指导班级
//        List<Grade> teacherGrades = new ArrayList<>();//授课班级
//        List<Student> teacherStudents = new ArrayList<>();//授课学生
//
        //1、获取session中用户信息类型
        User user = (User) httpSession.getAttribute("sessionUser");
        String sessionUserId = user.getUsername();
        String userType = user.getUserType();


        //3、转发至对应页面
        model.addAttribute("Id",sessionUser.getId());
        model.addAttribute("username",sessionUser.getUsername());
        model.addAttribute("userType",sessionUser.getUserType());
        model.addAttribute("userSex",sessionUser.getUserSex());
        model.addAttribute("userAge",sessionUser.getUserAge());


        return "personal/"+returnPage;
    }
	
}
